<template>
  <div class="text-case-tool">
    <div class="tool-header">
      <h1>英文字母大小写转换</h1>
      <p>快速转换英文字母的大小写格式</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 输入区域 -->
        <el-col :span="12">
          <div class="input-section">
            <div class="section-header">
              <h3>输入文本</h3>
              <div class="actions">
                <el-button @click="clearInput" size="small">清空</el-button>
                <el-button @click="pasteFromClipboard" size="small" type="primary">粘贴</el-button>
              </div>
            </div>

            <el-input v-model="inputText" type="textarea" :rows="8" placeholder="请输入要转换的英文文本..." @input="handleInput" />

            <div class="input-stats" v-if="inputText">
              <el-tag type="info" size="small">字符数: {{ inputText.length }}</el-tag>
              <el-tag type="success" size="small">单词数: {{ wordCount }}</el-tag>
            </div>
          </div>
        </el-col>

        <!-- 输出区域 -->
        <el-col :span="12">
          <div class="output-section">
            <div class="section-header">
              <h3>转换结果</h3>
              <div class="actions">
                <el-button @click="copyAllResults" size="small" :disabled="!hasResults">复制全部</el-button>
                <el-button @click="clearAllResults" size="small">清空</el-button>
              </div>
            </div>

            <div class="results-container">
              <div class="result-item">
                <div class="result-label">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  大写
                </div>
                <el-input v-model="results.uppercase" type="textarea" :rows="2" placeholder="大写转换结果..." readonly />
                <el-button @click="copyResult('uppercase')" size="small" :disabled="!results.uppercase">复制</el-button>
              </div>

              <div class="result-item">
                <div class="result-label">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  小写
                </div>
                <el-input v-model="results.lowercase" type="textarea" :rows="2" placeholder="小写转换结果..." readonly />
                <el-button @click="copyResult('lowercase')" size="small" :disabled="!results.lowercase">复制</el-button>
              </div>

              <div class="result-item">
                <div class="result-label">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  首字母大写
                </div>
                <el-input v-model="results.capitalize" type="textarea" :rows="2" placeholder="首字母大写转换结果..." readonly />
                <el-button @click="copyResult('capitalize')" size="small" :disabled="!results.capitalize">复制</el-button>
              </div>

              <div class="result-item">
                <div class="result-label">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  驼峰命名
                </div>
                <el-input v-model="results.camelCase" type="textarea" :rows="2" placeholder="驼峰命名转换结果..." readonly />
                <el-button @click="copyResult('camelCase')" size="small" :disabled="!results.camelCase">复制</el-button>
              </div>

              <div class="result-item">
                <div class="result-label">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  句子首字母大写
                </div>
                <el-input v-model="results.sentenceCase" type="textarea" :rows="2" placeholder="句子首字母大写转换结果..."
                  readonly />
                <el-button @click="copyResult('sentenceCase')" size="small"
                  :disabled="!results.sentenceCase">复制</el-button>
              </div>

              <div class="result-item">
                <div class="result-label">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  标题大小写
                </div>
                <el-input v-model="results.titleCase" type="textarea" :rows="2" placeholder="标题大小写转换结果..." readonly />
                <el-button @click="copyResult('titleCase')" size="small" :disabled="!results.titleCase">复制</el-button>
              </div>
            </div>

            <!-- 新文本框显示结果 -->
            <div v-if="options.showInNewBox" class="new-result-box" style="margin-top: 20px;">
              <div class="section-header">
                <h3>转换结果</h3>
                <div class="actions">
                  <el-button @click="copyNewResult" size="small" :disabled="!newResult">复制</el-button>
                  <el-button @click="clearNewResult" size="small">清空</el-button>
                </div>
              </div>
              <el-input v-model="newResult" type="textarea" :rows="8" placeholder="转换结果将显示在这里..." readonly />
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 转换选项 -->
      <div class="options-section">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>转换选项</span>
            </div>
          </template>
          <div class="options-content">
            <el-checkbox v-model="options.autoCopy" label="转换自动复制结果" />
            <el-checkbox v-model="options.showInNewBox" label="新文本框显示结果" />
            <el-checkbox v-model="options.enableCustomDict" label="添加原样输出词库" />
            <el-tooltip v-if="options.enableCustomDict" content="自定义词库仅支持首字母大写、句子首字母大写、标题大小写的转换" placement="top">
              <el-input v-model="customDict" type="textarea" :rows="2"
                placeholder="请输入要保持原样的单词，用逗号或换行分隔（如：API,URL,JSON）" style="margin-top: 10px;" />
            </el-tooltip>
          </div>
        </el-card>
      </div>

      <!-- 快速转换按钮 -->
      <div class="quick-actions">
        <el-button-group>
          <el-button @click="convertToUppercase" :disabled="!inputText">
            <el-icon>
              <Edit />
            </el-icon>
            转大写
          </el-button>
          <el-button @click="convertToLowercase" :disabled="!inputText">
            <el-icon>
              <Edit />
            </el-icon>
            转小写
          </el-button>
          <el-button @click="convertToCapitalize" :disabled="!inputText">
            <el-icon>
              <Edit />
            </el-icon>
            首字母大写
          </el-button>
          <el-button @click="convertToCamelCase" :disabled="!inputText">
            <el-icon>
              <Edit />
            </el-icon>
            驼峰命名
          </el-button>
          <el-button @click="convertToSentenceCase" :disabled="!inputText">
            <el-icon>
              <Edit />
            </el-icon>
            句子首字母大写
          </el-button>
          <el-button @click="convertToTitleCase" :disabled="!inputText">
            <el-icon>
              <Edit />
            </el-icon>
            标题大小写
          </el-button>
        </el-button-group>
      </div>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>

          <div class="info-content">
            <h4>转换类型说明：</h4>
            <ul>
              <li><strong>大写：</strong>将所有字母转换为大写形式</li>
              <li><strong>小写：</strong>将所有字母转换为小写形式</li>
              <li><strong>首字母大写：</strong>每个单词的首字母大写，其余小写（仅在英文单词前有空格的情况下才有效）</li>
              <li><strong>驼峰命名：</strong>将文本转换为驼峰命名格式（camelCase）</li>
              <li><strong>句子首字母大写：</strong>每句话的首字母大写，其余小写（仅在符号".!?:"后的第一个单词有效）</li>
              <li><strong>标题大小写：</strong>使用APA Style，所有单词首字母大写，除了不是标题第一个或最后一个单词的次要单词（如：a, an, the, and, but, or, for,
                nor, on,
                at, to, by, in, of, up, as, so, yet, off, if, per, via, out等）</li>
            </ul>

            <h4>程序上的字母大小写转换：</h4>
            <ul>
              <li><strong>PHP：</strong>strtolower() 字符串转换为小写，strtoupper() 字符串转换为大写；ucfirst() 将第一个字符转换为大写，ucwords()
                将每个单词的首字母转换为大写</li>
              <li><strong>JavaScript：</strong>toLowerCase() 返回所有字母转换为小写的字符串；toUpperCase() 返回所有字母转换为大写的字符串</li>
              <li><strong>Python：</strong>capitalize() 将第一个字母变成大写,其他字母变小写；upper() 将字符串中的小写字母转为大写字母；lower()
                转换所有大写字符为小写；title()
                返回"标题化"的字符串,所有单词都是以大写开始，其余字母均为小写</li>
            </ul>

            <h4>使用场景：</h4>
            <ul>
              <li>编程中的变量命名</li>
              <li>文档标题格式化</li>
              <li>数据库字段命名</li>
              <li>API接口命名规范</li>
            </ul>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'

const inputText = ref('')
const results = ref({
  uppercase: '',
  lowercase: '',
  capitalize: '',
  camelCase: '',
  sentenceCase: '',
  titleCase: ''
})

// 转换选项
const options = ref({
  autoCopy: false,
  showInNewBox: false,
  enableCustomDict: false
})

// 自定义词库
const customDict = ref('')

// 新文本框显示结果
const newResult = ref('')

// 次要单词列表（APA Style Title Case）
const minorWords = ['a', 'an', 'the', 'and', 'but', 'or', 'for', 'nor', 'on', 'at', 'to', 'by', 'in', 'of', 'up', 'as', 'so', 'yet', 'off', 'if', 'per', 'via', 'out']

const wordCount = computed(() => {
  if (!inputText.value.trim()) return 0
  return inputText.value.trim().split(/\s+/).length
})

const hasResults = computed(() => {
  return Object.values(results.value).some(result => result.trim())
})

const handleInput = () => {
  if (inputText.value.trim()) {
    convertAll()
  } else {
    clearAllResults()
  }
}

const convertAll = () => {
  const text = inputText.value
  const converted = {
    uppercase: text.toUpperCase(),
    lowercase: text.toLowerCase(),
    capitalize: capitalizeWords(text),
    camelCase: toCamelCase(text),
    sentenceCase: toSentenceCase(text),
    titleCase: toTitleCase(text)
  }

  results.value = converted

  // 如果启用新文本框显示结果，显示第一个非空结果
  if (options.value.showInNewBox) {
    const firstResult = Object.values(converted).find(r => r.trim())
    if (firstResult) {
      newResult.value = firstResult
    }
  }

  // 如果启用自动复制，复制第一个非空结果
  if (options.value.autoCopy) {
    const firstResult = Object.values(converted).find(r => r.trim())
    if (firstResult) {
      copyToClipboard(firstResult)
    }
  }
}

const convertToUppercase = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本')
    return
  }
  const result = inputText.value.toUpperCase()
  results.value.uppercase = result
  if (options.value.showInNewBox) {
    newResult.value = result
  }
  if (options.value.autoCopy) {
    copyToClipboard(result)
  }
  ElMessage.success('已转换为大写')
}

const convertToLowercase = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本')
    return
  }
  const result = inputText.value.toLowerCase()
  results.value.lowercase = result
  if (options.value.showInNewBox) {
    newResult.value = result
  }
  if (options.value.autoCopy) {
    copyToClipboard(result)
  }
  ElMessage.success('已转换为小写')
}

const convertToCapitalize = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本')
    return
  }
  const result = capitalizeWords(inputText.value)
  results.value.capitalize = result
  if (options.value.showInNewBox) {
    newResult.value = result
  }
  if (options.value.autoCopy) {
    copyToClipboard(result)
  }
  ElMessage.success('已转换为首字母大写')
}

const convertToCamelCase = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本')
    return
  }
  const result = toCamelCase(inputText.value)
  results.value.camelCase = result
  if (options.value.showInNewBox) {
    newResult.value = result
  }
  if (options.value.autoCopy) {
    copyToClipboard(result)
  }
  ElMessage.success('已转换为驼峰命名')
}

const convertToSentenceCase = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本')
    return
  }
  const result = toSentenceCase(inputText.value)
  results.value.sentenceCase = result
  if (options.value.showInNewBox) {
    newResult.value = result
  }
  if (options.value.autoCopy) {
    copyToClipboard(result)
  }
  ElMessage.success('已转换为句子首字母大写')
}

const convertToTitleCase = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本')
    return
  }
  const result = toTitleCase(inputText.value)
  results.value.titleCase = result
  if (options.value.showInNewBox) {
    newResult.value = result
  }
  if (options.value.autoCopy) {
    copyToClipboard(result)
  }
  ElMessage.success('已转换为标题大小写')
}

const capitalizeWords = (text) => {
  if (!text.trim()) return ''

  // 获取自定义词库
  const dictWords = getCustomDictWords()

  return text
    .toLowerCase()
    .replace(/\b\w/g, l => l.toUpperCase())
    .replace(/\b\w+/g, (word) => {
      // 如果单词在自定义词库中，保持原样
      if (dictWords.has(word.toLowerCase())) {
        return dictWords.get(word.toLowerCase())
      }
      return word
    })
}

const toCamelCase = (text) => {
  return text
    .toLowerCase()
    .replace(/[^a-zA-Z0-9]+(.)/g, (match, chr) => chr.toUpperCase())
}

// 句子首字母大写：每句话的首字母大写（仅在符号".!?:"后的第一个单词有效）
const toSentenceCase = (text) => {
  if (!text.trim()) return ''

  // 获取自定义词库
  const dictWords = getCustomDictWords()

  // 先处理句子首字母大写
  let result = text
    .toLowerCase()
    .replace(/(^|[.!?:]\s+)([a-z])/g, (match, prefix, char) => {
      return prefix + char.toUpperCase()
    })

  // 然后处理自定义词库
  if (dictWords.size > 0) {
    result = result.replace(/\b\w+\b/g, (word) => {
      // 如果单词在自定义词库中，保持原样
      if (dictWords.has(word.toLowerCase())) {
        return dictWords.get(word.toLowerCase())
      }
      return word
    })
  }

  return result
}

// 标题大小写（APA Style）：所有单词首字母大写，除了次要单词
const toTitleCase = (text) => {
  if (!text.trim()) return ''

  // 获取自定义词库
  const dictWords = getCustomDictWords()

  // 先找到所有单词及其索引
  const words = text.toLowerCase().match(/\b\w+\b/g) || []
  const nonWords = text.split(/\b\w+\b/)

  // 找到最后一个单词的索引
  const lastWordIndex = words.length - 1

  let result = ''
  let wordIndex = 0

  // 处理文本，保留非单词字符
  for (let i = 0; i < nonWords.length; i++) {
    result += nonWords[i]

    if (wordIndex < words.length) {
      const word = words[wordIndex]
      const lowerWord = word.toLowerCase()
      const isFirst = wordIndex === 0
      const isLast = wordIndex === lastWordIndex

      // 如果单词在自定义词库中，保持原样
      if (dictWords.has(lowerWord)) {
        result += dictWords.get(lowerWord)
      } else if (isFirst || isLast || !minorWords.includes(lowerWord)) {
        // 如果是第一个或最后一个单词，或者不是次要单词，则首字母大写
        result += word.charAt(0).toUpperCase() + word.slice(1)
      } else {
        // 否则保持小写
        result += word
      }

      wordIndex++
    }
  }

  return result
}

// 获取自定义词库单词集合
const getCustomDictWords = () => {
  const dict = new Map()
  if (!options.value.enableCustomDict || !customDict.value.trim()) {
    return dict
  }

  // 支持逗号、换行、空格分隔
  const words = customDict.value
    .split(/[,\n\s]+/)
    .map(w => w.trim())
    .filter(w => w)

  words.forEach(word => {
    const lower = word.toLowerCase()
    dict.set(lower, word) // 保持用户输入的原样
  })

  return dict
}

// 复制到剪贴板的辅助函数
const copyToClipboard = async (text) => {
  if (!text) return

  try {
    await navigator.clipboard.writeText(text)
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
  }
}

const clearInput = () => {
  inputText.value = ''
  clearAllResults()
  ElMessage.info('已清空输入内容')
}

const clearAllResults = () => {
  results.value = {
    uppercase: '',
    lowercase: '',
    capitalize: '',
    camelCase: '',
    sentenceCase: '',
    titleCase: ''
  }
  newResult.value = ''
}

const copyNewResult = async () => {
  if (!newResult.value) {
    ElMessage.warning('没有可复制的内容')
    return
  }

  try {
    await navigator.clipboard.writeText(newResult.value)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = newResult.value
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('已复制到剪贴板')
  }
}

const clearNewResult = () => {
  newResult.value = ''
  ElMessage.info('已清空新文本框')
}

const copyResult = async (type) => {
  const text = results.value[type]
  if (!text) {
    ElMessage.warning('没有可复制的内容')
    return
  }

  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('已复制到剪贴板')
  }
}

const copyAllResults = async () => {
  const allResults = Object.entries(results.value)
    .filter(([key, value]) => value.trim())
    .map(([key, value]) => `${key}: ${value}`)
    .join('\n\n')

  if (!allResults) {
    ElMessage.warning('没有可复制的内容')
    return
  }

  try {
    await navigator.clipboard.writeText(allResults)
    ElMessage.success('已复制全部结果到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const pasteFromClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText()
    inputText.value = text
    convertAll()
    ElMessage.success('已粘贴内容并自动转换')
  } catch (error) {
    ElMessage.error('无法访问剪贴板，请手动粘贴')
  }
}
</script>

<style scoped>
.text-case-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.input-section,
.output-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.actions {
  display: flex;
  gap: 8px;
}

.input-stats {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.results-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.result-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  color: #333;
  font-size: 0.9rem;
}

.result-item .el-input {
  flex: 1;
}

.result-item .el-button {
  align-self: flex-start;
}

.quick-actions {
  margin: 30px 0;
  text-align: center;
}

.options-section {
  margin: 100px 0;
}

.options-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tool-info {
  margin-top: 40px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .quick-actions .el-button-group {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .quick-actions .el-button {
    margin-bottom: 8px;
  }
}
</style>
